package com.atwork.wuhua.jpush;

import android.annotation.SuppressLint;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;

import com.atwork.wuhua.ConstantsMyself;
import com.atwork.wuhua.bean.PushExtrasBean;
import com.atwork.wuhua.utils.LogUtils;
import com.atwork.wuhua.utils.SPUtils;
import com.atwork.wuhua.utils.Util;
import com.google.gson.Gson;


import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.data.JPushLocalNotification;

public class MyJPushReceiver extends BroadcastReceiver {
    private static final String TAG = "ssss";
    private NotificationManager nm;

    @Override
    public void onReceive(Context context, Intent intent) {
        if (null == nm) {
            nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        }

        Bundle bundle = intent.getExtras();
        LogUtils.e("onReceive111 - " + intent.getAction() + ", extras111: " + printBundle(bundle));

        if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
            String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
            LogUtils.e("JPush用户注册成功==》" + regId);

        } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
            LogUtils.e("接受到推送下来的自定义消息");
            processCustomMessage(context, bundle);
        } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
            LogUtils.e("接受到推送下来的通知");

//            receivingNotification(context, bundle);

        } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
            LogUtils.e("用户点击打开了通知");

            openNotification(context, bundle);

        } else if (JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
            boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
            SPUtils.setString(context, SPUtils.NETWORK, connected + "");
        } else {
            LogUtils.e("Unhandled intent - " + intent.getAction());
        }
    }

    private void processCustomMessage(Context context, Bundle bundle) {
        String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
//        String extras = bundle.getString(JPushInterface.EXTRA_MESSAGE);
        LogUtils.e("processCustomMessage==>" + extras);
        if (extras != null && extras.length() > 0) {
            try {
                Gson gson = new Gson();
                PushExtrasBean entity = gson.fromJson(extras,
                        PushExtrasBean.class);
                JPushLocalNotification ln = new JPushLocalNotification();
                ln.setBuilderId(0);
                ln.setTitle(entity.getTitle());
                ln.setContent(entity.getContent());
                if (entity.getOrder_id() != null) {
                    ln.setNotificationId(Integer.valueOf(entity.getOrder_id()));
                }
                ln.setBroadcastTime(System.currentTimeMillis());
                Map<String, Object> map = new HashMap<>();
                map.put("data", extras);
                JSONObject json = new JSONObject(map);
                ln.setExtras(json.toString());
                JPushInterface.addLocalNotification(context.getApplicationContext(), ln);

            } catch (Exception e) {
            }
        }

    }

    private void receivingNotification(Context context, Bundle bundle) {
        String title = bundle.getString(JPushInterface.EXTRA_NOTIFICATION_TITLE);
        LogUtils.e(" title : " + title);
        String message = bundle.getString(JPushInterface.EXTRA_ALERT);
        LogUtils.e("message : " + message);
        String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
        LogUtils.e("extras : " + extras);
    }

    private void openNotification(Context context, Bundle bundle) {

        String extrasAll = bundle.getString(JPushInterface.EXTRA_EXTRA);
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(extrasAll);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String extras = jsonObject.optString("data");
        if (!TextUtils.isEmpty(extras)) {
            try {
                Gson gson = new Gson();
                PushExtrasBean entity = gson.fromJson(extras,
                        PushExtrasBean.class);
                Intent intent;
//
//                if (Util.isRunningForeground(context)) {
//                    if (entity.getType().equals("订单")) {
//                        intent = new Intent(context, OrderDetailActivity.class);
//                        intent.putExtra(ConstantsMyself.INTENTORDERID, entity.getOrder_id());
//                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                        context.startActivity(intent);
//                    } else if (entity.getType().equals("官方")) {
//                        intent = new Intent(context, NewsDetailActivity.class);
//                        intent.putExtra(ConstantsMyself.INTENTTYPE, 1);
//                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                        context.startActivity(intent);
//                    } else if (entity.getType().equals("账户")) {
//                        intent = new Intent(context, NewsDetailActivity.class);
//                        intent.putExtra(ConstantsMyself.INTENTTYPE, 1);
//                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                        context.startActivity(intent);
//                    }
//
//                } else {
//                    Intent mIntent = new Intent(context, SplashActivity.class);
//                    mIntent.putExtras(bundle);
//                    mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                    context.startActivity(mIntent);
//                }
            } catch (Exception e) {
            }


        }


    }

    // 打印所有的 intent extra 数据
    @SuppressLint("NewApi")
    private static String printBundle(Bundle bundle) {
        StringBuilder sb = new StringBuilder();
        for (String key : bundle.keySet()) {
            if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
            } else if (key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
            } else if (key.equals(JPushInterface.EXTRA_EXTRA)) {
                if (bundle.getString(JPushInterface.EXTRA_EXTRA).isEmpty()) {
                    LogUtils.e("This message has no Extra data");
                    continue;
                }

                try {
                    JSONObject json = new JSONObject(
                            bundle.getString(JPushInterface.EXTRA_EXTRA));
                    Iterator<String> it = json.keys();

                    while (it.hasNext()) {
                        String myKey = it.next().toString();
                        sb.append("\nkey:" + key + ", value: [" + myKey + " - "
                                + json.optString(myKey) + "]");
                    }
                } catch (JSONException e) {
                    LogUtils.e("Get message extra JSON error!");
                }

            } else {
                sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
            }
        }
        return sb.toString();
    }
}
